//
//  DiaryViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/10.
//

import Foundation
import SwiftUI
class DiaryViewModel: BaseViewModel {
    @Published var mediaItems: [MediaItem] = []
    @Published var bean: DiaryBean

    init(bean: DiaryBean) {
        self.bean = bean
        super.init()
        self.addObserve(self, .updateDiary) { (selfInstance, bean: DiaryBean) in
            selfInstance.bean = bean
            selfInstance.getPictureNet(bean: bean)
        }
        self.addObserve(self, .delDiary) { (selfInstance, bean: DiaryBean) in
            //过快关闭页面，会导致销毁功能不执行，
            pathManager.back()
        }
    }
    
    
    func getPicture(bean : DiaryBean) {
        mediaItems.removeAll()
        bean.listDiaryPicture?.forEach {
            if let mediaItem = DiaryExt.getMediaItem($0) {
                mediaItems.append(mediaItem)

            }
        }
    }

    //请求网络
    func getPictureNet(bean : DiaryBean) {
        request {
            let list = [bean]
            try await DiaryExt.dealPicture(list, true)
            return ""
        } suc: { _ in
            self.getPicture(bean: bean)
        } fail: {
            showToast($0.message)
        }
    }
}
